define([
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/searchBlock",
	"EasyUI","EasyUI-lang"
    ],function(Util,Tool,SearchBlock,Theme){

    var sysPath =  getServer() + "/static/app/fwsjcj";

    var zwFormHtml = sysPath + "/datamaintain/views/zwForm.html";
    var cityFormHtml = sysPath + "/datamaintain/views/cityForm.html";
	var getZwController = function(){
		return getServer() + "/fw/";
		
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
		createZwGrid();
        //浏览器窗口大小变化后，表格宽度自适应
        $(window).resize(function(){
            createZwGrid();
        });

	};
	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
            createZwGrid();
        });
        $("#btnReset").click(function () {
            $("#zwName").val("");
            $("#zwCode").val("");
        });
	};
	var createZwGrid = function() {
        $("#zwGrid").datagrid({
            url:getZwController() + "queryFwData",
			method:"GET",
            fitColumns: true,
            autoRowHeight: false,
            columns:[[
//				{field:"ck",checkbox:true},
                {field:'districtName',title:'省（直辖市）名称',width:'19%',align:'center',
                    formatter:function(value,rowData,rowIndex){
                    	var rowItem = JSON.stringify(rowData)
                        //return '<a href="#" onclick="_editZw(\'' + rowData.zwId+ '\');"> '+rowData.zwName+' </a> '
						return "<a href='#' onclick='_editZw(" + rowItem + ");'> "+rowData.districtName+" </a> "
                    }
                },
                {field:'allBuildingArea',title:'总建筑面积（万平方米）',width:'15%',align:'center',},
                {field:'amendatoryAllBuildingArea',title:'总建筑面积修正值（万平方米）',width:'15%',align:'center',
                	formatter:function(value,rowData,rowIndex){
                    	if(value == 0){
                    		return "";
                    	}else{
                    		return value;
                    	}
					}
                },

                {field:'areaIsOpen',title:'是否启用',width:'10%',align:'center',
                	formatter:function(value,rowData,rowIndex){
                    	if(value == "0"){
                    		return "是";
                    	}else if(value == "1"){
                    		return "否";
                    	}
					}	
                },
                {field:'allBuildingCount',title:'总栋数（栋）',width:'15%',align:'center',},
                {field:'amendatoryAllBuildingCount',title:'总栋数修正值（栋）',width:'15%',align:'center',
                	formatter:function(value,rowData,rowIndex){
                    	if(value == 0){
                    		return "";
                    	}else{
                    		return value;
                    	}
					}
                },
                {field:'countIsOpen',title:'是否启用',width:'10%',align:'center',
                	formatter:function(value,rowData,rowIndex){
                    	if(value == "0"){
                    		return "是";
                    	}else if(value == "1"){
                    		return "否";
                    	}
					}
            	},
            ]],
            toolbar: [{
                iconCls: 'fa fa-upload',
                text: "导入",
                handler: function () {
                    uploadZw()
                }
            }],
//          queryParams:{
//              zwName: $("#zwName").val(),
//              zwCode: $("#zwCode").val()
//          },
//          pagination: true,
//          pageSize: 10
        });
    };

//  var exportZw = function () {
//      window.location.href = getZwController() + "exportFile";
//  };

    var uploadZw = function () {
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal",function(){
//          var url = "http://localhost:8080" + getZwController() + "downloadTemplate";
			var url = getServer() + "/static/excel/房屋数据模板.xlsx";
            $("#downloadZwExcelTemplate").attr("href",url);
        });

        $('#uploadButton').off("click");
        $("#uploadButton").on("click",function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file",uploadinput.files[0]);
            $.ajax({
                url: getZwController() + "uploadFile" ,
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value=null;
                    Util.alert(data);
                    createZwGrid();
                }
            });
        });
    };
	var createCityGrid = function(province) {
		debugger
        $("#cityGrid").datagrid({
            url:getZwController() + "division/provinceCityFwData",
			method:"GET",
            fitColumns: true,
            autoRowHeight: false,
            columns:[[
//				{field:"ck",checkbox:true},
                {field:'belongtoCity',title:'市/区名称',width:'16%',align:'center',
                    formatter:function(value,rowData,rowIndex){
                    	var rowItem = JSON.stringify(rowData)
                        //return '<a href="#" onclick="_editZw(\'' + rowData.zwId+ '\');"> '+rowData.zwName+' </a> '
						return "<a href='#' onclick='_editCity(" + rowItem + "," + JSON.stringify(province) + ");'> "+rowData.belongtoCity+" </a> "
                    }
                },
                {field:'allBuildingArea',title:'总建筑面积（万平方米）',width:'18.5%',align:'center',},
                {field:'amendatoryAllBuildingArea',title:'总建筑面积修正值（万平方米）',width:'16%',align:'center',
                	formatter:function(value,rowData,rowIndex){
                    	if(value == 0){
                    		return "";
                    	}else{
                    		return value;
                    	}
					}
                },

                {field:'areaIsOpen',title:'是否启用',width:'10%',align:'center',
                	formatter:function(value,rowData,rowIndex){
                    	if(value == "0"){
                    		return "是";
                    	}else if(value == "1"){
                    		return "否";
                    	}
					}	
                },
                {field:'allBuildingCount',title:'总栋数（栋）',width:'15%',align:'center',},
                {field:'amendatoryAllBuildingCount',title:'总栋数修正值（栋）',width:'15%',align:'center',
                	formatter:function(value,rowData,rowIndex){
                    	if(value == 0){
                    		return "";
                    	}else{
                    		return value;
                    	}
					}
                },
                {field:'countIsOpen',title:'是否启用',width:'10%',align:'center',
                	formatter:function(value,rowData,rowIndex){
                    	if(value == "0"){
                    		return "是";
                    	}else if(value == "1"){
                    		return "否";
                    	}
					}
            	},
            ]],
//          toolbar: [{
//              iconCls: 'fa fa-plus-circle',
//              text:"添加",
//              handler: function(){addZw()}
//          },{
//              iconCls: 'fa fa-trash-o',
//              text:"删除",
//              handler: function(){deleteZw()}
//          }, {
//              iconCls: 'fa fa-upload',
//              text: "导入",
//              handler: function () {
//                  uploadZw()
//              }
//          },{
//              iconCls: 'fa fa-download',
//              text: "导出",
//              handler: function () {
//                  exportZw()
//              }
//          }],
            queryParams:{
                province: province,
            },
//          pagination: true,
//          pageSize: 10
        });
    };
	var formValidator = function(){
		//自定义validate验证输入的数字小数点位数不能大于两位
        jQuery.validator.addMethod("minNumber",function(value, element){
            var returnVal = true;
            inputZ=value;
            var ArrMen= inputZ.split(".");    //截取字符串
            if(ArrMen.length==2){
                if(ArrMen[1].length!=2){    //判断小数点后面的字符串长度
                    returnVal = false;
                    return false;
                }
            }
            return returnVal;
        },"小数点后为两位");         //验证错误信息
        jQuery.validator.addMethod("isInteger", function (value, element) {
            return this.optional(element) || (/^[-\+]?\d+$/.test(value) && parseInt(value) >= 0);
        }, "必须为正整数");
		$("#zwForm").validate({
			rules : {
				districtName : {
					required :true,					
				},
				areaIsOpen : {
					required :true,					
				},
				countIsOpen : {
					required :true,					
				},
                allBuildingArea : {
					required : true,
					number: true,
					minNumber : true
				},
				amendatoryAllBuildingArea : {
					required : true,
					number: true,
					minNumber : true
				},
                allBuildingCount:{
					required : true,
					isInteger: true    //调用自定义验证
				},
                amendatoryAllBuildingCount:{
					required : true,
					isInteger: true    //调用自定义验证
				}
			},
			messages : {
                districtName : {
					required:"省不允许为空!",
				},
				areaIsOpen : {
					required:"是否启用不允许为空!",
				},
                countIsOpen : {					
					required:"是否启用不允许为空!",
				},
				amendatoryAllBuildingArea : {					
					required:"总建筑面积修正值不允许为空!",
				},
                allBuildingCount : {					
					required:"总栋数不允许为空!",
				},
				amendatoryAllBuildingCount : {					
					required:"总栋数修正值不允许为空!",
				},
			}
		});
	};
	var formValidatorCity = function(){
		//自定义validate验证输入的数字小数点位数不能大于两位
        jQuery.validator.addMethod("minNumber",function(value, element){
            var returnVal = true;
            inputZ=value;
            var ArrMen= inputZ.split(".");    //截取字符串
            if(ArrMen.length==2){
                if(ArrMen[1].length!=2){    //判断小数点后面的字符串长度
                    returnVal = false;
                    return false;
                }
            }
            return returnVal;
        },"小数点后为两位");         //验证错误信息
        jQuery.validator.addMethod("isInteger", function (value, element) {
            return this.optional(element) || (/^[-\+]?\d+$/.test(value) && parseInt(value) >= 0);
        }, "必须为正整数");
		$("#cityForm").validate({
			rules : {
				belongtoCity : {
					required :true,					
				},
				areaIsOpen : {
					required :true,					
				},
				countIsOpen : {
					required :true,					
				},
                allBuildingArea : {
					required : true,
					number: true,
					minNumber : true
				},
				amendatoryAllBuildingArea : {
					required : true,
					number: true,
					minNumber : true
				},
                allBuildingCount:{
					required : true,
					isInteger: true    //调用自定义验证
				},
                amendatoryAllBuildingCount:{
					required : true,
					isInteger: true    //调用自定义验证
				}
			},
			messages : {
                belongtoCity : {
					required:"市/区不允许为空!",
				},
				areaIsOpen : {
					required:"是否启用不允许为空!",
				},
                countIsOpen : {					
					required:"是否启用不允许为空!",
				},
                allBuildingArea : {					
					required:"总建筑面积不允许为空!",
				},
				amendatoryAllBuildingArea : {					
					required:"总建筑面积修正值不允许为空!",
				},
                allBuildingCount : {					
					required:"总栋数不允许为空!",
				},
				amendatoryAllBuildingCount : {					
					required:"总栋数修正值不允许为空!",
				},
			}
		});
	};
	var getZw = function(item){
		console.log(item)
		if(item.amendatoryAllBuildingArea==0){
			item.amendatoryAllBuildingArea = "";
		}
		if(item.amendatoryAllBuildingCount==0){
			item.amendatoryAllBuildingCount = "";
		}
		Tool.deserialize("zwForm", item);
//		$.ajax({
//			url: getZwController() + "/"+id,
//			type: "get",
//			success: function (data) {
//				Tool.deserialize("zwForm", data);
//			}
//		});
	};
	var getCity = function(item){
		console.log(item)
		if(item.amendatoryAllBuildingArea==0){
			item.amendatoryAllBuildingArea = "";
		}
		if(item.amendatoryAllBuildingCount==0){
			item.amendatoryAllBuildingCount = "";
		}
		Tool.deserialize("cityForm", item);
//		$.ajax({
//			url: getZwController() + "/"+id,
//			type: "get",
//			success: function (data) {
//				Tool.deserialize("zwForm", data);
//			}
//		});
	};

//	var addZw = function () {
//		var slidebar = Util.slidebar({
//			url: zwFormHtml,
//			width: "580px",
//			cache: false,
//			close : true,
//			afterLoad: function () {
//				formValidator();
//				$("#saveBtn").on("click", function () {
//					if($("#zwForm").valid()){
//						var data = Tool.serialize("zwForm");
//						$.ajax({
//							url: getZwController() ,
//                          contentType:"application/json",
//							data: JSON.stringify(data),
//							type: "post",
//							success: function (data) {
//								Util.alert(data);
//								slidebar.close();
//                              createZwGrid();
//							}
//						});
//					}
//				});
//			}
//		});
//	};
	window._editZw = function(zwId) {
		var slidebar = Util.slidebar({
			url: zwFormHtml,
			width: "900px",
			cache: false,
			close : true,
			afterOpen: function () {
				if(zwId.districtName!="全国"){
					createCityGrid(zwId.districtName);
				}
				
			},
			afterLoad: function () {
				formValidator();
				getZw(zwId);
				$("#saveBtn").on("click", function () {
					if($("#zwForm").valid()){
						var data = Tool.serialize("zwForm");
						$.ajax({
							url: getZwController() + "updateDataByDistrict",
                            contentType:"application/json",
                            data: JSON.stringify(data),
							type: "post",
							success: function (data) {
								Util.alert(data);
								slidebar.close();
								createZwGrid();
							}
						});
					}
				});
			}
		});
	};
	window._editCity = function(zwId,province) {
		debugger
		var slidebar = Util.slidebar({
			url: cityFormHtml,
			width: "580px",
			cache: false,
			close : true,
			afterLoad: function () {
				formValidatorCity();
				getCity(zwId);
				$("#saveBtnCity").on("click", function () {
					if($("#cityForm").valid()){
						var data = Tool.serialize("cityForm");
						data.districtName = province;
						$.ajax({
							url: getZwController() + "division/updateDataByCity",
                            contentType:"application/json",
                            data: JSON.stringify(data),
							type: "post",
							success: function (data) {
								Util.alert(data);
								slidebar.close();
								createCityGrid(province);
							}
						});
					}
				});
			}
		});
	};
	var deleteZw = function() {
		var rows = $("#zwGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}
		Util.confirm("是否要删除选中的职务?", function() {
			var ids = "";
			$.each(rows, function(i, row){
				ids += row.zwId + ",";
			});
			ids = ids.substr(0,ids.length - 1);
			$.ajax({
				url: getZwController() ,
				data: {
					ids : ids
				},
				type: "delete",
				success: function (data) {
					createZwGrid();
				}
			});
		}, function() {
			return;
		});

	};

	return {
		init:init
	};
});
